package vue;

import gestionSites.Site;
import gestionSites.SiteListHandler;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;

import aspiration.FileDownloader;
import aspiration.SiteCapturer;


/**
 * panneau d'onglets en bas de l'application
 * permet de g�rer un t�l�chargement
 *
 */
public class CapturerView extends JTabbedPane {
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * onglet de t�l�chargement
	 */
	protected CapturerSettingsView  settingView;
	
	/**
	 * onglet de filtrage
	 */
	protected FilterView filterView;
	
	/**
	 * onglet d'aide
	 */
	protected HelpView helpView, helpViewEn;
	
	/**
	 * onglet de t�l�chargement
	 */
	protected DLView dlView;
	
	/**
	 * v�rification d'une url
	 * @param u url
	 * @return renvoie true si l'url est valide
	 */
	private static boolean checkURL(String u){
		
		Pattern p = Pattern.compile(
			        new StringBuilder()
			                .append("((?:(http|https|Http|Https):")
			                .append("\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)")
			                        .append("\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_")
			                        .append("\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?")
			                        .append("((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}\\.)+")   // named host
			                        .append("(?:")   // plus top level domain
			                        .append("(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])")
			                        .append("|(?:biz|b[abdefghijmnorstvwyz])")
			                        .append("|(?:cat|com|coop|c[acdfghiklmnoruvxyz])")
			                        .append("|d[ejkmoz]")
			                        .append("|(?:edu|e[cegrstu])")
			                        .append("|f[ijkmor]")
			                        .append("|(?:gov|g[abdefghilmnpqrstuwy])")
			                        .append("|h[kmnrtu]")
			                        .append("|(?:info|int|i[delmnoqrst])")
			                        .append("|(?:jobs|j[emop])")
			                        .append("|k[eghimnrwyz]")
			                        .append("|l[abcikrstuvy]")
			                        .append("|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])")
			                        .append("|(?:name|net|n[acefgilopruz])")
			                        .append("|(?:org|om)")
			                        .append("|(?:pro|p[aefghklmnrstwy])")
			                        .append("|qa")
			                        .append("|r[eouw]")
			                        .append("|s[abcdeghijklmnortuvyz]")
			                        .append("|(?:tel|travel|t[cdfghjklmnoprtvwz])")
			                        .append("|u[agkmsyz]")
			                        .append("|v[aceginu]")
			                        .append("|w[fs]")
			                        .append("|y[etu]")
			                        .append("|z[amw]))")
			                        .append("|(?:(?:25[0-5]|2[0-4]") // or ip address
			                        .append("[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]")
			                        .append("|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1]")
			                        .append("[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}")
			                        .append("|[1-9][0-9]|[0-9])))")
			                        .append("(?:\\:\\d{1,5})?)") // plus option port number
			                        .append("(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~")  // plus option query params
			                        .append("\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?")
			                        .append("(?:\\b|$)").toString()
			                );
		
		return p.matcher(u).matches();
		
	}
	
	/**
	 * constructeur
	 * @param siteList site de listes
	 */
	public CapturerView(SiteListHandler siteList) {
		
		JButton launch=new JButton("Launch Capture");
		
		settingView = new CapturerSettingsView(siteList,launch);
		filterView = new FilterView();
		helpView = new HelpView(HelpView.FR);	
		helpViewEn = new HelpView(HelpView.EN);
		
		this.add("Settings",settingView);
		this.add("Filters",filterView);
		this.add("Help (EN)", helpViewEn);
		this.add("Aide (FR)",helpView);
		
		this.setPreferredSize(new Dimension(800,190)); 
	
		final SiteListHandler finalSLH = siteList;
		launch.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
		
				if (settingView.getname().isFilled()){
					if(settingView.getAddress().isFilled()) {
						if (settingView.getDepth().isFilled()) {
							
			
				
							String address = settingView.getAddress().getText();
							
							if(!checkURL(address)){
								
								JOptionPane.showMessageDialog(null, "Malformed url","Error detected",JOptionPane.ERROR_MESSAGE);
								return;
							}
							
							if (!address.endsWith("/"))
								address = address + "/";
							
							Site site = new Site(address, settingView.getTarget(), Integer.valueOf(settingView.getDepth().getText()),settingView.getname().getText().replaceAll(" ", ""));
							
							FileDownloader fd = new FileDownloader(site.getTarget()+"/"+site.getName() , site.getSourceString());
							
							int maxsize = filterView.getMSV().getTailleMax()*1024;
							
							SiteCapturer sc = new SiteCapturer(site,filterView.creerFiltre(fd),finalSLH,maxsize);
		
							DLView dlview = new DLView(sc);
							add("Downloading "+site.getName(), dlview.getPanel());
							setSelectedComponent(dlview.getPanel());
							
							sc.start();
						}else{
							JOptionPane.showMessageDialog(null, "Missing website depth","Error detected",JOptionPane.ERROR_MESSAGE);
						}
					}else{
						JOptionPane.showMessageDialog(null, "Missing website url","Error detected",JOptionPane.ERROR_MESSAGE);
					}
				}else{
					JOptionPane.showMessageDialog(null, "Missing website name","Error detected",JOptionPane.ERROR_MESSAGE);					
				}
				
			}
		});
	
	}

	/**
	 * acc�s � l'onglet de t�l�chargement
	 * @return onglet de t�l�chargement
	 */
	public CapturerSettingsView getSettingView() {
		return settingView;
	}
	

}
